<template>
  <el-dialog
      title="新增试题"
      :close-on-click-modal="false"
      :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="120px">
      <el-form-item label="课程" prop="courseId">
        <el-select v-model="dataForm.courseId" placeholder="请选择题所属课程">
          <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="附件" prop="content">
        <el-form-item label="" prop="name">
          <el-upload
              class="upload-demo"
              :limit="1"
              :http-request="uploadFile"
              :on-success="handleSuccess"
              :on-error="handleError">
            <el-button slot="trigger" icon="el-icon-upload" size="small" type="primary">上传试题</el-button>
          </el-upload>
        </el-form-item>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {fetchQuestionList, uploadQuestion} from '@/api/teacher/workQuestion'
import {fetchCourseList} from "@/api/teacher/course";
import store from "@/store";

export default {
  data() {
    return {
      courseList: [],
      visible: false,
      canSubmit: false,
      file: '',
      dataForm: {
        courseId: ''
      },
      dataRule: {
        courseId: [
          {required: true, message: '课程不能为空！', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getCourseList()
  },
  methods: {
    getCourseList() {
      fetchCourseList().then(response => {
        this.courseList = response.data
      })
    },
    init(id) {
      this.visible = true;
      this.canSubmit = true;
      this.$refs['dataForm'].resetFields()
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const formDatas = new FormData();
          if (this.file) {
            formDatas.append("file", this.file);
            formDatas.append("courseId", this.dataForm.courseId);
          }
          uploadQuestion(formDatas).then(data => {
            this.$notify.success('添加成功')
            this.visible = false
            this.$emit('refreshDataList')
          }).catch(() => {
            this.canSubmit = true;
          });
        }
      })
    },
    uploadFile(param) {
      this.file = param.file;
    },
    handleSuccess(response, file, fileList) {
      this.dataForm.url = response.data
      this.dataForm.userId = store.getters.token.split(",")[2]
    },
    handleError(err, file, fileList) {
      console.error('Error during upload:', err);
    }
  }
}
</script>
